//
//  DiscoverSecondViewController.m
//  陶瓷
//
//  Created by 郭天龙 on 15/7/11.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "DiscoverSecondViewController.h"
#import "JobCell.h"
#import "MarketCell.h"
#import "ShopCell.h"
#import "TCNetworkTool.h"
#import "DiscoverJobViewController.h"
#import "DiscoverMarketViewController.h"
#import "DiscoverSecondViewController.h"
#import "DiscoverJobViewController.h"
#import "DiscoverShopViewController.h"
#import "MarketModel.h"
#import "AddMessageController.h"

#import "MJRefresh.h"

typedef NS_ENUM(NSInteger, TableType) {
    JobTableType,
    ShopTableType,
    MarketTableType,
};

typedef NS_ENUM(NSInteger, RefreshType) {
    PullUpRefresh,
    PushDownRefresh,
};


@interface DiscoverSecondViewController ()<UITableViewDelegate,UITableViewDataSource,MarketCellDelegate>

@property (nonatomic, weak) IBOutlet UIButton *leftButton;
@property (nonatomic, weak) IBOutlet UIButton *rightButton;
@property (nonatomic, weak) IBOutlet UITableView *tableview;

@property (nonatomic, assign) int pn;
@property (nonatomic, assign) BOOL allCityState;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *cover;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *distanceOfTableViewToBottom;

@property (nonatomic, strong) UIButton *addBtn;
@end

@implementation DiscoverSecondViewController

#pragma mark - MarketCellDelegate
- (void)didMarketCellWithDic:(MarketModel *)markmodel
{
    DiscoverMarketViewController *markVC = [[DiscoverMarketViewController alloc] init];
    markVC.sid = markmodel.Id;
    [self.navigationController pushViewController:markVC animated:YES];
}


#pragma mark - Action
- (IBAction)clickAllCityButton:(id)sender
{
    _allCityState = YES;
    //    [self.tableview.header beginRefreshing];
    [self refreshTableDataSource:_tableType withState:PushDownRefresh];
    [self.leftButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.leftButton setImage:[UIImage imageNamed:@"wb_infolist_tap_all_pressed.png"] forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.rightButton setImage:[UIImage imageNamed:@"wb_infolist_tap_near_normal.png"] forState:UIControlStateNormal];
}

- (IBAction)clickNearCityButton:(id)sender
{
    _allCityState = NO;
    //    [self.tableview.header beginRefreshing];
    [self refreshTableDataSource:_tableType withState:PushDownRefresh];
    [self.rightButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.rightButton setImage:[UIImage imageNamed:@"wb_infolist_tap_near_pressed.png"] forState:UIControlStateNormal];
    [self.leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.leftButton setImage:[UIImage imageNamed:@"wb_infolist_tap_all_normal.png"] forState:UIControlStateNormal];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.tableType) {
        case JobTableType:
        {
            //            self.title = @"招聘";
            JobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JobCell"];
            cell = [[NSBundle mainBundle] loadNibNamed:@"JobCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row > [self.dataArray count]) {
                return cell;
            }
            [cell setModel:[self.dataArray objectAtIndex:indexPath.row]];
            return cell;
        }
            break;
        case ShopTableType:
        {
            //            self.title = @"商铺";
            ShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopCell"];
            cell = [[NSBundle mainBundle] loadNibNamed:@"ShopCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row > [self.dataArray count]) {
                return cell;
            }
            [cell setModel:[self.dataArray objectAtIndex:indexPath.row]];
            return cell;
        }
            break;
        case MarketTableType:
        {
            //            self.title = @"市场";
            MarketCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MarketCell"];
            //            cell = [[NSBundle mainBundle] loadNibNamed:@"MarketCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.dataArray.count > indexPath.row) {
                [cell setModel:[self.dataArray objectAtIndex:indexPath.row]];
            }
            cell.delegate = self;
            return cell;
        }
            break;
            
        default:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"discovercell"];
            
            cell = [[UITableViewCell alloc] init];
            return cell;
        }
            break;
    }
    
}



#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.tableType) {
        case 0:
            return 80;
            break;
        case 1:
            return 110;
            break;
        case 2:
            return 180;
            break;
        default:
            return 30;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.tableType) {
        case 0:
        {
            DiscoverJobViewController *jobvc = [[DiscoverJobViewController alloc] init];
            jobvc.sid = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"Id"];
            [self.navigationController pushViewController:jobvc animated:YES];
        }
            break;
        case 1:
        {
            DiscoverShopViewController *shopVC = [[DiscoverShopViewController alloc] init];
            shopVC.sid = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"Id"];
            [self.navigationController pushViewController:shopVC animated:YES];
        }
            break;
        default:
            break;
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    
    self.pn = 1;
    self.allCityState = YES;
    
    __weak UITableView *tableView = self.tableview;
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pn = 1;
        [self refreshTableDataSource:_tableType withState:PushDownRefresh];
    }];
    tableView.header.autoChangeAlpha = YES;
    tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pn += 1;
        [self refreshTableDataSource:_tableType withState:PullUpRefresh];
    }];
    
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
    [self.tableview registerNib:[UINib nibWithNibName:@"JobCell" bundle:nil] forCellReuseIdentifier:@"JobCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"MarketCell" bundle:nil] forCellReuseIdentifier:@"MarketCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"ShopCell" bundle:nil] forCellReuseIdentifier:@"ShopCell"];
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"discovercell"];
    
    self.dataArray = [[NSMutableArray alloc] init];
    self.tableview.tableFooterView = [UIView new];
    [self.leftButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.leftButton setImage:[UIImage imageNamed:@"wb_infolist_tap_all_pressed.png"] forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.rightButton setImage:[UIImage imageNamed:@"wb_infolist_tap_near_normal.png"] forState:UIControlStateNormal];
    [self refreshTableDataSource:_tableType withState:PushDownRefresh];
    
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    addBtn.frame = CGRectMake(0, 0, 30,30);
    [addBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    _addBtn = addBtn;
}

- (IBAction)sendMessage {
    if (IsLoginIn) {
        AddMessageController *tcIssue = [[AddMessageController alloc] init];
        
        switch (_tableType) {
            case JobTableType: {
                tcIssue.questionArray = recruitmentQuestionArray;
                tcIssue.title = @"招聘信息发布";
            }
                break;
            case ShopTableType: {
                tcIssue.questionArray = rentQuestionArray;
                tcIssue.title = @"商铺信息发布";
            }
                break;
            default:
                break;
        }
        [self.navigationController pushViewController:tcIssue animated:YES];
    } else {
        self.tabBarController.selectedIndex = 4;
    }
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _addBtn.hidden = !(self.tableType == ShopTableType || self.tableType == JobTableType);
    switch (self.tableType) {
        case JobTableType:
            [self.navigationItem setTitle:@"人才招聘"];
//            _distanceOfTableViewToBottom.constant = 49;
            break;
        case ShopTableType:
            [self.navigationItem setTitle:@"转让招租"];
//            _distanceOfTableViewToBottom.constant = 49;
            break;
        case MarketTableType:
            [self.navigationItem setTitle:@"市场分布"];
//            _distanceOfTableViewToBottom.constant = 0;
            break;
            
        default:
            break;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationItem setTitle:@""];
    [super viewWillDisappear:animated];
    [self.cover removeFromSuperview];
    [SVProgressHUD dismiss];
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor clearColor];
    }
    return _cover;
}

- (void)viewDidAppear:(BOOL)animated
{
    
}


- (void)refreshTableDataSource:(int)type withState:(RefreshType)state
{
    [SVProgressHUD showWithStatus:@"正在获取数据 请稍后.."];
    [self.view addSubview:self.cover];
    TCBaseTool *base = [TCBaseTool sharedBaseTool];
    NSString *cityid = [[NSString alloc] init];
    if (!self.allCityState && base.currentCityId) {
        cityid = base.currentCityId;
    }
    else
    {
        cityid = @"";
    }
    switch (self.tableType) {
        case 0:
        {
            TCNetworkTool *net = [TCNetworkTool sharedNetTool];
            [net getJobListWithPn:[NSString stringWithFormat:@"%d",self.pn] andCity:cityid SuccessBlocks:^(NSArray *resultArray) {
                [self refreshSuccessWithState:state andData:resultArray];
                [self.cover removeFromSuperview];
            } andFailureBlocks:^(NSString *failureMessage) {
                [SVProgressHUD dismiss];
                [self refreshFailedWithState:state];
                [MBHUDHelper showWarningWithText:failureMessage];
            }];
        }
            break;
        case 1:
        {
            TCNetworkTool *net = [TCNetworkTool sharedNetTool];
            [net getShopListWithPn:[NSString stringWithFormat:@"%d",self.pn] andCity:cityid SuccessBlocks:^(NSArray *resultArray) {
                [self refreshSuccessWithState:state andData:resultArray];
            } andFailureBlocks:^(NSString *failureMessage) {
                [SVProgressHUD dismiss];
                [self refreshFailedWithState:state];
                [MBHUDHelper showWarningWithText:failureMessage];
            }];
        }
            break;
        case 2:
        {
            TCNetworkTool *net = [TCNetworkTool sharedNetTool];
            [net getMarketListWithPn:[NSString stringWithFormat:@"%d",self.pn] andCity:cityid SuccessBlocks:^(NSArray *resultArray) {
                [self refreshMarketSuccessWithState:state andData:resultArray];
            } andFailureBlocks:^(NSString *failureMessage) {
                [SVProgressHUD dismiss];
                [self refreshFailedWithState:state];
                [MBHUDHelper showWarningWithText:failureMessage];
            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)refreshFailedWithState:(RefreshType)state
{
    [self.cover removeFromSuperview];
    if (state == PushDownRefresh) {
        [self.tableview.header endRefreshing];
    }
    else
    {
        [self.tableview.footer endRefreshing];
    }
}

- (void)refreshSuccessWithState:(RefreshType)state andData:(NSArray *)resultArray
{
    [SVProgressHUD dismiss];
    [self.cover removeFromSuperview];
    
    if (state == PushDownRefresh) {
        if ([self.dataArray count] > 0) {
            [self.dataArray removeAllObjects];
        }
        if (resultArray && resultArray.count > 0) {
            self.dataArray = [resultArray mutableCopy];
        }
        [self.tableview.header endRefreshing];
    }
    else
    {
        if (resultArray && resultArray.count > 0) {
            [self.dataArray addObjectsFromArray:resultArray];
        }
        [self.tableview.footer endRefreshing];
    }
    [self.tableview reloadData];
}

- (void)refreshMarketSuccessWithState:(RefreshType)state andData:(NSArray *)resultArray
{
    [SVProgressHUD dismiss];
    [self.cover removeFromSuperview];
    if (state == PushDownRefresh) {
        if ([self.dataArray count] > 0) {
            [self.dataArray removeAllObjects];
        }
        if (resultArray && resultArray.count > 0) {
            NSMutableArray *mutArr = [[NSMutableArray alloc] initWithCapacity:2];
            __weak NSMutableArray *array = _dataArray;
            [resultArray enumerateObjectsUsingBlock:^(NSArray *obj, NSUInteger idx, BOOL *stop) {
                [mutArr addObject:obj];
                if ([mutArr count] == 2) {
                    [array addObject:[mutArr mutableCopy]];
                    [mutArr removeAllObjects];
                }
                if ((idx == [resultArray count]-1) && [mutArr count] > 0) {
                    [array addObject:mutArr];
                }
            }];
        }
        self.tableview.backgroundColor = [UIColor colorWithString:@"#F8F8F8"];
        [self.tableview.header endRefreshing];
    }
    else
    {
        if (resultArray && resultArray.count > 0) {
            NSMutableArray *mutArr = [[NSMutableArray alloc] initWithCapacity:2];
            __weak NSMutableArray *array = _dataArray;
            [resultArray enumerateObjectsUsingBlock:^(NSArray *obj, NSUInteger idx, BOOL *stop) {
                [mutArr addObject:obj];
                if ([mutArr count] == 2) {
                    [array addObject:[mutArr mutableCopy]];
                    [mutArr removeAllObjects];
                }
                if ((idx == [resultArray count]-1) && [mutArr count] > 0) {
                    [array addObject:mutArr];
                }
            }];
        }
        
        self.tableview.backgroundColor = [UIColor colorWithString:@"#F8F8F8"];
        [self.tableview.footer endRefreshing];
    }
    [self.tableview reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
